<template>
  <div class="user-info-page">
    <el-form ref="userInfo" :model="userInfo" :rules="personalRules"  label-width="120px" autocomplete="on" label-position="left">
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="userInfo.userName" style="width: 300px;" />
      </el-form-item>
      <el-form-item label="性别" prop="userSex">
        <el-select v-model="userInfo.userSex" style="width: 300px;">
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="年龄" prop="userAge">
        <el-input v-model="userInfo.userAge"  style="width: 300px;"/>
      </el-form-item>
      <el-form-item label="身份证号码" prop="idCardNumber">
        <el-input v-model="userInfo.idCardNumber" disabled style="width: 300px;"/>
      </el-form-item>
      <el-form-item label="联系方式" prop="userPhone">
        <el-input v-model="userInfo.userPhone" style="width: 300px;" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="userInfo.password" style="width: 300px;" />
      </el-form-item>
    </el-form>
    <el-button type="primary" :disabled="isFormInvalid" style="margin-left: 120px; width: 100px;" @click="updateData">修改</el-button>
    <el-button type="primary" :disabled="isFormInvalid" style="margin-left: 80px; width: 100px;" @click="logOutUser">退出登录</el-button>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import store from '@/store'
import { getUserInfoByToken,updatePersonalInfo,tfExistName,logout} from '@/api/user'; // 假设存在这样一个接口用于根据 token 获取用户信息
export default {
  data() {
    return {
      Xtoken:{"X-Token":store.getters.token},
      userInfo: {
        userName: '',
        userSex: '',
        userAge: '',
        idCardNumber: '',
        userPhone: '',
        password:'',
        facePhoto:''
      },
      dialogImageUrl: '',
      dialogVisible: false,
      hasAvatar: false, // 新增状态变量
      fileList: [],
      personalRules: {
        userName: [{ required: true, trigger: 'change', validator: this.validateUsername.bind(this) }],
        userSex: [{ required: true, trigger: 'change' }],
        userAge: [{ required: true, trigger: 'change', validator: this.validateAge.bind(this) }],
        userPhone: [{ required: true, trigger: 'change', validator: this.validatePhone.bind(this) }],
        password: [{ required: true, trigger: 'change', validator: this.validatePassword.bind(this) }],
      },
      isFormInvalid: false // 初始设为true，表单验证通过后再设为false
    };
  },
 
  created() {
    this.fetchUserInfo(this.token);

  },
  computed: {
    ...mapGetters(['token', 'avatar'])
  },
  methods: {
    handleRemove(file, fileList) {
      this.dialogImageUrl = ''
      this.dialogVisible = false
      this.fileList = []
      this.hasAvatar = false // 重置 hasAvatar 状态
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      if (!isImage) {
        this.$message.error('只能上传图片文件!')
      }
      return isImage
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件`)
    },
    onSubmit() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          await this.$store
            .dispatch('user/resetUser', this.form)
            .then(response => {
              const { data } = response
              this.$message({
                message: response.msg,
                type: 'success'
              })
              this.form = data
              this.reset = data
            })
          this.$router.push('/')
        } else {
          return false
        }
      })
    },
    removeAvatar() {
      this.fileList = []
      this.hasAvatar = false
    },
    fetchUserInfo(token) {
      console.log("个人信息token:"+token)
      getUserInfoByToken(token).then(response => {
        console.log("getUserInfoByToken:"+token)
        this.userInfo = response.data;
        if (this.avatar) {
          console.log(this.avatar);
          
        this.fileList = [
          {
            url:this.avatar
          }
        ]
        this.hasAvatar = true
        console.log(this.hasAvatar);
      }
      }).catch(error => {
        console.log("getUserInfoByToken:"+token)
        console.error('获取用户信息失败：', error);
      });
    },
    validateUsername(rule, value, callback) {
      if (value === '') {
        callback(new Error('用户名不能为空'));
        this.isFormInvalid=true
        return;
      }
      tfExistName(this.userInfo.userName,this.token).then(response => {
        if (response.data.valid) {
          this.isFormInvalid=false
          callback();
        } else {
          this.isFormInvalid=true
          callback(new Error('用户名已存在，请重新输入'));
        }
      }).catch(() => {
        callback(new Error('验证用户名时出现错误，请稍后再试'));
        this.isFormInvalid=true
      });
    },
    validateAge(rule, value, callback) {
      if (!value || value < 0 || value > 120) {
        this.isFormInvalid=true
        callback(new Error('请输入合法的年龄'));
      } else {
        this.isFormInvalid=false
        callback();
      }
    },
    validatePassword(rule, value, callback) {
      if (value.length < 6 || value.length > 15) {
        callback(new Error('密码长度应大于6，小于15'));
        this.isFormInvalid=true
      } else {
        this.isFormInvalid=false
        callback();
      }
    },
    validatePhone(rule, value, callback) {
      const phoneRegex = /^1[3-9]\d{9}$/;
      if (!value ||!phoneRegex.test(value)) {
        this.isFormInvalid=true
        callback(new Error('请输入正确的手机号码'));
      } else {
        this.isFormInvalid=false
        callback();
      }
    },
    updateData() {
        let token = sessionStorage.getItem('token');
        console.log("updateData:"+token)
            //临时数据   内容拷贝到tempData
            const tempData = Object.assign({}, this.userInfo)
            updatePersonalInfo(tempData,token).then(() => {
             // this.list.splice(index, 1, this.temp)
             this.fetchUserInfo(token);
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
    },
    logOutUser(){
      logout().then(response => {
          if(response.msg=='操作成功'){
              window.location.href = '/login';
          }else {
              console.error('未获取到有效的token，无法执行注销操作');
              alert('您尚未登录，无需注销');
          }
      })
    }
  
  },
  
};
</script>

<style scoped>
.user-info-page {
  padding: 20px;
}
</style>